"use strict";
const utils = require('../utils/util');
const methodEnums = {
	addEventListener: 'addEventListener',
	removeEventListener: 'removeEventListener',
};

module.exports = {
	meta: {
		docs: {
			description: "remind removeEventListener after addEventListener",
			category: "Best Practices",
			recommended: false
		},
		fixable: null,
		schema: [
		]
	},
	create: function(context) {
		let addListeners = [], removeListeners = [];
		return {
			CallExpression(node) {
				const member = utils.getCallExpression(node);
				const eventType = utils.getEventTypeName(node);
				if (member && member.methodName === methodEnums.addEventListener) {
					addListeners.push({
						targetName: member.targetObj,
						methodName: member.methodName,
						node,
						eventType,
					});
				}
				if(member &&  member.methodName === methodEnums.removeEventListener) {
					removeListeners.push({
						targetName: member.targetObj,
						methodName: member.methodName,
						node,
						eventType,
					});
				}
			},
			'Program:exit'() {
				if (addListeners.length > 0) {
					addListeners.forEach(obj => {
						const removeListener = removeListeners.find(item => item.targetName === obj.targetName && item.eventType === obj.eventType);
						if (!removeListener) { // 没找到remove
							context.report(obj.node, `请别忘记移除${obj.targetName}的${obj.eventType}监听`);
						}
					});
				}
			},
		}
	},
};